﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace ETWebApi2.Models
{
    /// <summary>
    /// 限制单个IP短时间内访问次数
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class IPActionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 限制单个IP短时间内访问次数
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string ip = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress;
            //var isValid = IPCacheHelper.CheckIsAble(ip);
            IPCacheInfoModel ipModel =  IPCacheHelper.GetIPLimitInfo(ip);
            if (!ipModel.IsVisit)
            {
                //Logger.Warn(string.Format("IP【{0}】被限制了【{1}】次数",ipModel.IP,ipModel.Limit));
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, "请不要频繁登陆，稍候再试。");
                return;
            }
            base.OnActionExecuting(actionContext);
        }

    }

    public class IPCacheInfoModel
    {
        /// <summary>
        /// IP 
        /// </summary>
        public string IP { get; set; }

        /// <summary>
        /// 限制次数
        /// </summary>
        public int Limit { get; set; }

        /// <summary>
        /// 是否可以访问
        /// </summary>
        public bool IsVisit { get; set; }

        /// <summary>
        /// 访问时间
        /// </summary>
        private List<DateTime> reqTime = new List<DateTime>();

        /// <summary>
        /// 访问时间
        /// </summary>
        public List<DateTime> ReqTime
        {
            get { return this.reqTime; }
            set { this.reqTime = value; }
        }
    }
}